<?php

namespace app\merchant\job;

use app\common\controller\Platurl;
use app\common\model\Agent;
use app\common\model\CardFans;
use app\common\model\CardGeneral;
use app\common\model\CardMember;
use app\common\model\Merchant;
use app\common\model\Momerchant;
use app\common\model\OpenTemplate;
use app\common\model\System;
use app\common\model\WxOpen;
use think\Queue;
use think\queue\Job;
use think\Session;
use Wechat\Wxobjopen;

class Start
{

    public function fire(Job $job, $data)
    {
//        file_put_contents('/data2/html/payos/exelog/test/' . 'task_tpl_card'.date("Y-m-d") . '.txt',  '0-1:' . json_encode($data, JSON_UNESCAPED_UNICODE).PHP_EOL, FILE_APPEND);

        $isJobDone = $this->task_tpl_card($data);
        $job->delete();

        if ($isJobDone) {
            //如果任务执行成功， 记得删除任务
            $job->delete();
            return '完成';
        } else {
            if ($job->attempts() > 3) {
                //通过这个方法可以检查这个任务已经重试了几次了
                print("<warn>任务已完成3次!" . "</warn>\n");
                $job->delete();
                // 也可以重新发布这个任务
                //print("<info>Hello Jobmach will be availabe again after 2s."."</info>\n");
                //$job->release(2); //$delay为延迟时间，表示该任务延迟2秒后再执行
            }
        }
    }



    /**
     * 根据消息中的数据进行实际的业务处理
     * @param array|mixed $data 发布任务时自定义的数据
     * @return boolean                 任务执行的结果
     */


    //群发模版消息
    public function task_tpl_card($data)
    {
//        file_put_contents('/data2/html/payos/fireuser.txt', 's1'.json_encode($data), FILE_APPEND);
//        file_put_contents('/data2/html/payos/exelog/test/' . 'task_tpl_card'.date("Y-m-d") . '.txt',  '0-2:' . json_encode($data, JSON_UNESCAPED_UNICODE).PHP_EOL, FILE_APPEND);

//        return $data;
        if (isset($data['top_mid'])) {
            $Momerchant = new Momerchant();
//        $mid = $this->getmid($data['card_id']);
            $top_mid = $data['top_mid'];

            $wx_open_id = $Momerchant->where('id', $top_mid)->value('wx_open_id');

            //按设置更新
//            $Platurl = new Platurl();
//            $options = $Platurl->getagenttplmsg($data['top_mid']);
            //初始化微信类
            $options = $this->options($data['card_id']);
            $weObj = new Wxobjopen($options);
            //模板ID
            $OpenTemplate = new OpenTemplate();
            $templateid = $OpenTemplate->where(['type' => 'card_zs_tpl', 'wx_open_id' => $wx_open_id])->value('template_id');
            //    return $templateid;
            $template['touser'] = $data['openid'];
            $template['template_id'] = $templateid;
            $Platurl = new Platurl();
            $agent_url = $Platurl->getagenturl('card_id',$data['card_id']);
//            file_put_contents('/data2/html/payos/fireuser.txt', 'start-1' . json_encode($agent_url), FILE_APPEND);
            $template['url'] = $agent_url."/mobile.php/carduser/addcard/card_id/" . $data['card_id'] . "/openid/" . $data['openid'];
            $template['topcolor'] = "#7B68EE";
//        $template['data'] =
            $template['data']['first'] = ['value' => $data['first'], 'color' => "#743A3A"];
            $template['data']['keyword1'] = ['value' => $data['nickname'], 'color' => '#000'];
            $template['data']['keyword2'] = ['value' => $data['title'], 'color' => '#FF0000'];
            $template['data']['keyword3'] = ['value' => date("Y-m-d H:i:s", time()), 'color' => '#000'];
            $template['data']['remark'] = ['value' => $data['remark'], 'color' => '#743A3A'];

            //发送
            $res = $weObj->sendTemplateMessage($template);
//        file_put_contents('/data/html/payos/test.txt','s2'.json_encode($res),8);
            return $res;
        }
    }

    public function failed($data)
    {


    }

    public function get_open_id()
    {
        $top_mid = Session::get('login_top_mid');
        $Momerchant = new Momerchant();
        $wx_open_id = $Momerchant->where('id', $top_mid)->value('wx_open_id');
        return $wx_open_id;
    }

    public function getmid($card_id)
    {
        $CardMember = new CardMember();
        $CardGeneral = new CardGeneral();
        $top_mid = $CardMember->where(['card_id' => $card_id])->value('mid');
        if (empty($top_mid)) {
            $top_mid = $CardGeneral->where(['card_id' => $card_id])->value('mid');
            return $top_mid;
        } else {
            return $top_mid;
        }
    }

    //获取代理商域名
//    public function getagenturl($card_id){
//        $CardMember = new CardMember();
//        $Merchant = new Merchant();
//        $Agent=new Agent();
//        $mid = $CardMember->where('card_id', $card_id)->value('mid');
//        $agent_id = $Merchant->where(['id'=>$mid])->value('agent');
//        $agent_url = $Agent->where(['id'=>$agent_id])->value('open_url');
//        return 'https://'.$agent_url;
//    }

    public function option()
    {
        Session::set('openid', null);
        //      $sarr = Session::get('user');
        $top_mid = Session::get('login_top_mid');
        $Momerchant = new Momerchant();
        $System = new System();
        $WxOpen = new WxOpen();
        $wx_open_id = $Momerchant->where('id', $top_mid)->value('wx_open_id');
        $config = $System->where(['id' => 1])->find();
        $users = $WxOpen->where(['id' => $wx_open_id])->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );
        return $options;
    }


    //微信API参数  根据card_id获取
    public function options($card_id)
    {
        //  Session::set('openid', null);
        $CardMember = new CardMember();
        $CardGeneral = new CardGeneral();
        $Merchant = new Merchant();
        $System = new System();
        $WxOpen = new WxOpen();
        $mid = $CardMember->where('card_id', $card_id)->value('mid');
        if ($mid) {
            $map['id'] = $mid;
        } else {
            $map['id'] = $CardGeneral->where('card_id', $card_id)->value('mid');
        }
        $mab['id'] = $Merchant->where($map)->value('wx_open_id');
        $config = $System->where(array('id' => 1))->find();
        $users = $WxOpen->where($mab)->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );
        return $options;
    }

    public function getagenturl($type,$param){
//        file_put_contents('/data2/html/payos/fireuser.txt', 'start-1' . json_encode($param), FILE_APPEND);
        $CardMember = new CardMember();
        $Merchant = new Merchant();
        $Agent=new Agent();
        $Momerchant = new Momerchant();

        switch($type){
            case "card_id":
                $mid = $CardMember->where('card_id', $param)->value('mid');
                if (!$mid){
                    $CardGeneral = new CardGeneral();
                    $mid = $CardGeneral->where('card_id', $param)->value('mid');
                }
                $agent_id = $Merchant->where(['id'=>$mid])->value('agent');
                $agent_url = $Agent->where(['id'=>$agent_id])->value('open_url');
                break;
            case "top_mid":
                $agent_id = $Momerchant->where('id', $param)->value('agent');
                $agent_url = $Agent->where(['id'=>$agent_id])->value('open_url');
                break;
        }
//        file_put_contents('/data2/html/payos/fireuser.txt', 'start-2' . json_encode($agent_url), FILE_APPEND);
        return 'https://'.$agent_url;

    }

}
